/**
 * Baijiahulian.com Inc.
 * Copyright (c) 2014-2016 All Rights Reserved.
 */
package com.baijia.authentication.handler.support;

import com.baijia.authentication.handler.exception.AuthenticationException;
import com.baijia.authentication.handler.exception.UrlMessageException;
import com.baijia.authentication.principal.Credentials;
import com.baijia.authentication.principal.credentials.MobileCredentials;
import com.baijia.services.impl.RegisteredServiceImpl;
import com.baijia.util.JigouPasswordUtil;

import com.baijia.util.MobileLoginUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Properties;

/**
 * @title MobileHackAuthenticationHandler
 * @desc 一种Hack的方式用于应对app store审核使用的测试账号，这个风险非常大
 * @author macrohuang
 * @date Jan 20, 2016
 * @version 1.0
 */
@Component
public class MobileHackAuthenticationHandler extends MobileAuthenticationHandler {

    @Autowired
    private Properties hackMobilePassword;

    @Override
    protected boolean preAuthenticate(Credentials credentials) throws AuthenticationException {
        MobileCredentials mobileCredentials = (MobileCredentials) credentials;
        RegisteredServiceImpl service =
                (RegisteredServiceImpl) servicesManager.findServiceBy(mobileCredentials.getAccountType());

        if (MobileLoginUtil.isUserBlockHack(mobileCredentials.getUsername())){
            throw new UrlMessageException("banned", "账号已被锁定，请1小时后再试！");
        }else if (!MobileLoginUtil.canUserLoginHack(mobileCredentials.getUsername())){
            throw new UrlMessageException("banned","登录过于频繁，请1分钟后再试！");
        }else if (MobileLoginUtil.getUserRetriesHack(mobileCredentials.getUsername())>service.getLoginMaxTimes()){
            throw new UrlMessageException("banned", "超过最大重试次数，用户将被禁止登录1小时！");
        }
        return true;
    }


    /* (non-Javadoc)
     * @see com.baijia.authentication.handler.support.AbstractPreAndPostProcessingAuthenticationHandler#doAuthentication(com.baijia.authentication.principal.Credentials)
     */
    @Override
    protected boolean doAuthentication(Credentials credentials) throws AuthenticationException {
        MobileCredentials userCredentials = (MobileCredentials) credentials;
        String mobile = userCredentials.getUsername();
        String passcode = userCredentials.getPasscode();
        try {
            return hackMobilePassword != null && hackMobilePassword.containsKey(mobile)
                && JigouPasswordUtil.validatePassword(passcode, hackMobilePassword.getProperty(mobile));
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            logger.error("Can't auth", e);
            return false;
        }
    }

    @Override
    protected boolean postAuthenticate(Credentials credentials, boolean authenticated) throws AuthenticationException {
        MobileCredentials mobileCredentials = (MobileCredentials) credentials;
        if (!authenticated) {
            MobileLoginUtil.incRetryHack(mobileCredentials.getUsername());
            int failTimes = MobileLoginUtil.getUserRetriesHack(mobileCredentials.getUsername());
            RegisteredServiceImpl service =
                    (RegisteredServiceImpl) servicesManager.findServiceBy(mobileCredentials.getAccountType());
            if (failTimes >= service.getLoginMaxTimes()) {
                MobileLoginUtil.blockUserHack(mobileCredentials.getUsername(), service.getBanSeconds());
                throw new UrlMessageException("banned", "账号已被锁定，请1小时后再试！");
            } else {
                throw new UrlMessageException("badCredential", "手机号与密码不符！");
            }
        } else {
            MobileLoginUtil.delUserRetriesHack(mobileCredentials.getUsername());
        }
        return authenticated;
    }
}
